from dao.DAOQuanLyNhanVien import DaoQuanLyNhanVien
from datetime import datetime as dt
import datetime
from google.appengine.api import users
from google.appengine.ext import db
from models.LoaiNhanVien import LoaiNhanVien
from models.NhanVien import NhanVien
from models.ThuChi import ThuChi
from utils.permission_required import permission_required
import WSGI
import json as simplejson
import logging
import math
import webapp2
from utils.Const import TrangThaiGiaBan

logger = logging.getLogger("GUIQuanLyNhanVien")

class GuiQuanLyThuChi(webapp2.RequestHandler):
    
    perm = 'KeToan.QuanLyThuChi'
    priv = ''
    @permission_required
    def get(self):
        
        nv = DaoQuanLyNhanVien.getNhanVienByUsername(users.get_current_user().nickname())
        lstPerm = DaoQuanLyNhanVien.getListStaffPriviledge(nv.key().id())
        lstMenu = []
        lstNewPerm = []
        for perm in lstPerm:
            lstMenu.append(perm[:perm.index('.')])
            lstNewPerm.append(perm.replace('.', '-'))
        lstMenu = list(set(lstMenu))
        
        cbbTenNV, _ = DaoQuanLyNhanVien.getListNhanVien('', '', 1000, 0, '')
        lstNV = ''
        for i in range(0, cbbTenNV.__len__()):
            cbbTenNV[i]['tenNV'] = str(cbbTenNV[i]['id']) + ' - ' + cbbTenNV[i]['tenNV']
            lstNV += str(cbbTenNV[i]['id']) + ':' + cbbTenNV[i]['tenNV'] + ';'
        lstNV = lstNV[:-1]  
        
        template_values = {
                        'priv': self.priv,
                        'lstNV': lstNV,
                        'lstPerm': lstNewPerm,
                        'lstMenu': lstMenu,
                        'nickname': users.get_current_user().nickname(),
                        'signOutUrl': users.create_logout_url(self.request.uri)
        }

        template = WSGI.jinja_environment.get_template('/html/QuanLyThuChi.html')
        self.response.out.write(template.render(template_values))


class JsonRequestHandler(webapp2.RequestHandler):
    perm = 'KeToan.QuanLyThuChi'
    priv = ''
    @permission_required
    def get(self):
        funcName = self.request.get('func')
        funcMapping = {'getListThuChi': 'getListThuChi',
                       'updateThuChi': 'updateThuChi'}
        func = getattr(self, funcMapping[funcName]);
        result = func();
        self.response.out.write(result)
    
    def post(self):
        return self.get()
    
    def getListThuChi(self):
        gridRowNum = int(self.request.get('rows'))
        pageNum = int(self.request.get('page'))
        fromDate = self.request.get('tuNgay')
            
        toDate = self.request.get('denNgay')
        
        rows, rowNum = DaoQuanLyNhanVien.getListThuChi(fromDate, toDate, gridRowNum, int((pageNum-1)*gridRowNum))
        
        results = {'page': pageNum, 'total': math.ceil(float(rowNum)/gridRowNum), 'records':rowNum, 'rows':rows}
        return simplejson.dumps(results)
    
    def updateThuChi(self):
        id = self.request.get('id')
        if id != '_empty':
            thuChi = ThuChi.get_by_id(int(id))
        else:
            thuChi = ThuChi()
            nv = DaoQuanLyNhanVien.getNhanVienByUsername(users.get_current_user().nickname())
            thuChi.nhanVien = str(nv.key().id()) + ' - ' + nv.tenNV
        oper = self.request.get('oper')
        logger.debug(oper)
        if oper != 'delete':
            thuChi.ngay = (dt.now() + datetime.timedelta(hours=7)).date()
            thuChi.soTien = float(self.request.get('soTien'))
            thuChi.ghiChu = self.request.get('ghiChu')
            
            if self.priv == 'Staff':
                thuChi.trangThai = TrangThaiGiaBan.CHUA_DUYET
            elif self.priv == 'Owner':
                thuChi.trangThai = self.request.get('trangThai')
            
            DaoQuanLyNhanVien.updateThuChi(thuChi)
        return 1
        
        
            
        